//
//  AuothVC.swift
//  WBSwift
//
//  Created by maker on 2016/11/11.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit
import SVProgressHUD

class AuothVC: UIViewController {
    //MARK:==========属性==========
    
    @IBOutlet weak var webView: UIWebView!
    
    //MARK:==========生命周期==========
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.设置导航
        setNavigatinBar()
        
        //2.加载网页
        let auothUrl = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        
        webView.loadRequest(URLRequest(url: (URL(string: auothUrl))!))
        webView.delegate = self
    }
}

//MARK:==========设置 UI ==========
extension AuothVC {
    func setNavigatinBar() {
        //1.设置左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(AuothVC.leftClick))
        //2.设置右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(AuothVC.rightClick))
        //3.设置中间标题
        navigationItem.title = "登录界面"
        
    }
}

//MARK:==========监听事件==========
extension AuothVC {
   @objc fileprivate func leftClick() {
        dismiss(animated: true, completion: nil)
    }
   @objc fileprivate func rightClick() {
//        let jsCode0 = "document.getElementById('userId').value='qingmingan@sina.com';document.getElementById('passwd').value='viviweiwei';"
            let jsCode = "document.getElementById('userId').value='17091931516@163.com';document.getElementById('passwd').value='liujiaqi123';"
//        let jsCode1 = "document.getElementById('userId').value='18353430686';document.getElementById('passwd').value='TIanqing815';"
        webView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
}

//MARK:==========webview 代理==========
extension AuothVC:UIWebViewDelegate{
    
    //1.开始加载网页
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //2.完成网页加载
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //3.网页加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //4.准备加载网页调用此方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.获取网页中的 URL
        guard let urlString = request.url?.absoluteString else {
            return true
        }
        
        //2.判断字符串中是否包含 code
        guard urlString.contains("code=") else {
            return true
        }
        
        //3.截取 code
        guard let code = urlString.components(separatedBy: "code=").last else {
            return true
        }
        
        //4.发送获取 accessToken 的网络请求
        getToken(code)
        return false
        
    }
}

//MARK:========== 请求数据 ==========
extension AuothVC{
    //1.获取 accesstoken
    func getToken(_ code:String) {
        print(code);
        NetWorkTool.shareInstance.getToken(code) { (result, error) in
            
            if error != nil{
                print(error as Any)
                return
            }
            guard let accounInfo = result else {
                return
            }
            
            let user = UserInfo(dict: accounInfo)
            self.getUserInfo(user)
            
        }
    }
    
    //2.获取用户信息
    func getUserInfo(_ user:UserInfo) {
        //1.从 user 中获取到 accesstoken
        guard let token = user.access_token else {
            return
        }
        //2.从 user 中获取到 uid
        guard let uid = user.uid else {
            return
        }
        
        //3.发送网络请求
        NetWorkTool.shareInstance.getUserInfo(token, uid: uid) { (result, error) in
            guard let userDict = result else{
                return
            }
            //3.1 给用户模型赋值
            user.screen_name = userDict["screen_name"] as? String
            user.avatar_large = userDict["avatar_large"] as? String
            
            //3.2对用户进行归档
            if NSKeyedArchiver.archiveRootObject( user, toFile: UserInfoViewModel.shareInstance.homePath) {
            }
            
            //3.3给用户单例赋值用户信息
            UserInfoViewModel.shareInstance.user = user
            
            //3.4 弹出欢迎界面
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeVC()
            })
            
        }
    }
}

